package com.example.munidingwei

import android.Manifest
import android.os.Build
import android.os.Bundle
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import com.example.munidingwei.ui.components.*
import com.example.munidingwei.ui.theme.MunidingweiTheme

class MainActivity : ComponentActivity() {
    private val requestPermissionLauncher = registerForActivityResult(
        ActivityResultContracts.RequestMultiplePermissions()
    ) { permissions ->
        val allGranted = permissions.values.all { it }
        // 这里可以通过ViewModel处理权限结果
    }
    
    // 后台位置权限请求
    private val backgroundPermissionLauncher = registerForActivityResult(
        ActivityResultContracts.RequestPermission()
    ) { isGranted ->
        if (isGranted) {
            Log.d("MainActivity", "✅ 后台位置权限已授予")
        } else {
            Log.e("MainActivity", "❌ 后台位置权限被拒绝 - 后台将无法获取位置！")
            // 显示提示
            android.app.AlertDialog.Builder(this)
                .setTitle("需要后台位置权限")
                .setMessage("为了在后台持续上报位置，需要授予\"始终允许\"访问位置的权限。\n\n请在设置中选择\"始终允许\"。")
                .setPositiveButton("去设置") { _, _ ->
                    startActivity(android.content.Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS).apply {
                        data = android.net.Uri.fromParts("package", packageName, null)
                    })
                }
                .setNegativeButton("取消", null)
                .show()
        }
    }
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        
        // 第一步：请求前台位置权限和通知权限
        val permissions = mutableListOf(
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION
        )
        
        // Android 13+ 需要通知权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            permissions.add(Manifest.permission.POST_NOTIFICATIONS)
            Log.d("MainActivity", "添加通知权限请求 (Android 13+)")
        }
        
        requestPermissionLauncher.launch(permissions.toTypedArray())
        
        // 第二步：请求后台位置权限（Android 10+必须单独请求）
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            Log.d("MainActivity", "⚠️ Android 10+，需要单独请求后台位置权限")
            requestBackgroundLocationPermission()
        }
        
        // 第三步：请求电池优化白名单
        requestBatteryOptimizationWhitelist()
        
        // 🚀 自动启动真实位置上报服务
        Log.d("MainActivity", "========================================")
        Log.d("MainActivity", "🚀 启动真实位置上报服务")
        Log.d("MainActivity", "========================================")
        RealLocationForegroundService.start(this)
        
        setContent {
            MunidingweiTheme {
                LocationApp()
            }
        }
    }
    
    /**
     * 请求后台位置权限（Android 10+必须）
     */
    private fun requestBackgroundLocationPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            // 延迟1秒后请求（等待前台权限授予）
            android.os.Handler(android.os.Looper.getMainLooper()).postDelayed({
                Log.d("MainActivity", "📱 请求后台位置权限...")
                backgroundPermissionLauncher.launch(Manifest.permission.ACCESS_BACKGROUND_LOCATION)
            }, 1000)
        }
    }
    
    /**
     * 请求加入电池优化白名单
     */
    private fun requestBatteryOptimizationWhitelist() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            val intent = android.content.Intent().apply {
                action = android.provider.Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS
                data = android.net.Uri.parse("package:$packageName")
            }
            
            try {
                Log.d("MainActivity", "📱 请求电池优化白名单...")
                startActivity(intent)
            } catch (e: Exception) {
                Log.e("MainActivity", "无法打开电池优化设置: ${e.message}")
            }
        }
    }
}

@Composable
fun LocationApp(
    viewModel: LocationViewModel = viewModel()
) {
    val uiState by viewModel.uiState.collectAsState()
    val context = LocalContext.current
    
    // 处理权限请求
    LaunchedEffect(Unit) {
        if (!uiState.hasLocationPermission) {
            viewModel.requestLocationPermission()
        }
    }
    
    Scaffold(
        modifier = Modifier.fillMaxSize()
    ) { innerPadding ->
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(innerPadding)
                .verticalScroll(rememberScrollState())
                .padding(16.dp),
            verticalArrangement = Arrangement.spacedBy(16.dp)
        ) {
            // 应用标题
            Text(
                text = "模拟定位应用",
                style = MaterialTheme.typography.headlineMedium,
                modifier = Modifier.padding(bottom = 8.dp)
            )
            
            // 地址搜索卡片
            SearchAddressCard(
                onSearch = { address -> viewModel.searchAddress(address) },
                onClear = { viewModel.clearSearchResults() },
                searchResults = uiState.searchResults,
                onResultSelected = { result -> viewModel.selectSearchResult(result) },
                isSearching = uiState.isSearching
            )
            
            // 位置信息卡片
            LocationCard(
                location = uiState.currentLocation,
                isSimulating = uiState.isSimulating
            )
            
            // 百度地图显示
            BaiduMapView(
                currentLocation = uiState.currentLocation,
                isSimulating = uiState.isSimulating,
                modifier = Modifier
                    .fillMaxWidth()
                    .height(300.dp),
                onLocationSelected = { lat, lng ->
                    // 点击地图时，设置模拟位置（内部会自动启用Mock Provider）
                    viewModel.setSystemMockLocation(lat, lng, 5.0f)
                }
            )
            
            // 操作按钮
            ActionButtons(
                onGetLocation = { viewModel.getCurrentLocation() },
                onSimulateLocation = { viewModel.showSimulationDialog() },
                onSystemMockLocation = { viewModel.showSystemMockDialog() },
                onStopSimulation = { viewModel.stopSimulation() },
                onShowHistory = { viewModel.showHistoryDialog() },
                onClearHistory = { viewModel.clearHistory() },
                onConnectBackend = { viewModel.showBackendDialog() },
                onServerConfig = { viewModel.showServerConfigDialog() },
                isSimulating = uiState.isSimulating,
                isConnectedToBackend = uiState.isConnectedToBackend
            )
        }
    }
    
    // 模拟位置对话框
    if (uiState.showSimulationDialog) {
        SimulationDialog(
            onDismiss = { viewModel.hideSimulationDialog() },
            onSimulate = { lat, lng -> viewModel.simulateLocation(lat, lng) }
        )
    }
    
    // 系统级模拟对话框
    if (uiState.showSystemMockDialog) {
        SystemMockDialog(
            onDismiss = { viewModel.hideSystemMockDialog() },
            onEnableSystemMock = { viewModel.enableSystemMockLocation() },
            onSetSystemMock = { lat, lng, acc -> viewModel.setSystemMockLocation(lat, lng, acc) },
            systemMockStatus = viewModel.getSystemMockStatus(),
            hasMockPermission = true, // 在Android 6.0+中不再需要此权限
            isSystemMockEnabled = viewModel.isSystemMockEnabled()
        )
    }
    
    // 位置历史对话框
    if (uiState.showHistoryDialog) {
        LocationHistoryDialog(
            history = uiState.locationHistory,
            onDismiss = { viewModel.hideHistoryDialog() }
        )
    }
    
    // 后台连接对话框
    if (uiState.showBackendDialog) {
        BackendConnectionDialog(
            onDismiss = { viewModel.hideBackendDialog() },
            onConnect = { serverUrl -> 
                viewModel.connectToBackend(serverUrl)
            },
            onDisconnect = { viewModel.disconnectFromBackend() },
            isConnected = uiState.isConnectedToBackend
        )
    }
    
    // 服务器配置对话框
    if (uiState.showServerConfigDialog) {
        ServerConfigDialog(
            currentUrl = uiState.currentServerUrl,
            isConnected = uiState.isConnectedToBackend,
            onDismiss = { viewModel.hideServerConfigDialog() },
            onSave = { url -> viewModel.saveServerUrl(url) },
            onConnect = { url -> viewModel.connectToBackend(url) },
            onDisconnect = { viewModel.disconnectFromBackend() }
        )
    }
}

@Preview(showBackground = true)
@Composable
fun LocationAppPreview() {
    MunidingweiTheme {
        LocationApp()
    }
}